package com.jh.paymentchannel.service;

import com.google.common.collect.Maps;
import com.jh.paymentchannel.business.BranchbankBussiness;
import com.jh.paymentchannel.business.TopupPayChannelBusiness;
import com.jh.paymentchannel.pojo.JFApiRegister;
import com.jh.paymentchannel.util.Util;
import com.jh.paymentchannel.util.jifuquick.AES;
import com.jh.paymentchannel.util.jifuquick.Base64;
import com.jh.paymentchannel.util.jifuquick.HttpClient4Util;
import net.sf.json.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Service
public class JFAPITopupRequest implements TopupRequest{

	private static final Logger log = LoggerFactory.getLogger(JFAPITopupRequest.class);
	
	@Autowired
	private TopupPayChannelBusiness topupPayChannelBusiness;
	
	@Autowired
	private BranchbankBussiness branchbankBussiness;
	
	@Autowired
	private Util util;
	
	@Value("${payment.ipAddress}")
	private String ipAddress;
	
	@Value("${jfapi.partnerNo}")
	private String partnerNo;
	
	@Value("${jfapi.key}")
	private String Key;
	
	@Value("${jfapi.url}")
	private String JFurl;
	
	//private static String partnerNo = "XL0APID0";
	
	//private static String Key = "0123456789abcdefghijklmnopqrstuv";
	
	//private String JFurl = "http://fast.jfpays.xyz:19084";
	
	private static final Charset UTF_8 = StandardCharsets.UTF_8;
	
	@Override
	public Map<String, String> topupRequest(HttpServletRequest request, String amount, String ordercode,
			String orderdesc, String extra, String notifyurl, String returnurl, String channelParam) throws Exception {
		log.info("我是全局替换的ipAddress=========="+ipAddress);
		log.info("partnerNo====="+partnerNo);
		log.info("Key====="+Key);
		log.info("JFurl====="+JFurl);
		 	Map<String, String>  map = new HashMap<String, String>();
			RestTemplate restTemplate=new RestTemplate();
			URI uri = util.getServiceUrl("transactionclear", "error url request!");
			String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
			MultiValueMap<String, String> requestEntity  = new LinkedMultiValueMap<String, String>();
			requestEntity.add("order_code", ordercode);
			String result = restTemplate.postForObject(url, requestEntity, String.class);
			log.info("RESULT================"+result);
			JSONObject jsonObject;
			JSONObject resultObj;
			try {
				jsonObject = JSONObject.fromObject(result);
				resultObj = jsonObject.getJSONObject("result");
			} catch (Exception e) {
				log.error("查询订单信息出错");
				map.put("resp_code", "failed");
				map.put("channel_type", "jfapi");
				map.put("resp_message", "没有该订单信息");
				return map;
			}
			String realamount = resultObj.getString("realAmount");
			String userid = resultObj.getString("userid");
			//通道id
			String channelid = resultObj.getString("channelid");
			//费率
			String rate = resultObj.getString("rate");
			//银行卡(充值卡)
			String bankCard = resultObj.getString("bankcard");
			
			restTemplate=new RestTemplate();
			uri = util.getServiceUrl("user", "error url request!");
			url = uri.toString() + "/v1.0/user/bank/default/userid";
			requestEntity  = new LinkedMultiValueMap<String, String>();
			requestEntity.add("user_id", userid);
			result = restTemplate.postForObject(url, requestEntity, String.class);
			
			log.info("RESULT================"+result);
			try {
				jsonObject =  JSONObject.fromObject(result);
				resultObj  =  jsonObject.getJSONObject("result");
			} catch (Exception e) {
				log.error("查询默认结算卡出错");
				map.put("resp_code", "failed");
				map.put("channel_type", "jfapi");
				map.put("resp_message", "查询默认结算卡有误");
				return map;
			}
			
			if(resultObj.isNullObject()){
				
				map.put("resp_code", "failed");
				map.put("channel_type", "jfapi");
				map.put("resp_message", "没有结算卡");
				return map;
			}
			
			//默认提现卡卡号
			String cardNo = resultObj.getString("cardNo");
			String userName = resultObj.getString("userName");
			/**身份证号*/
			String idcard   = resultObj.getString("idcard");
			String phone    = resultObj.getString("phone");
			//开户行所在省
			String provinceOfBank = resultObj.getString("province");
			
			System.out.println("provinceOfBank"+provinceOfBank);
			//开户行所在市
			String cityOfBank = resultObj.getString("city");
			
			System.out.println("cityOfBank"+cityOfBank);
			//银行名称
			String bankName = resultObj.getString("bankName");
			//支行名称
			String bankBranchName = resultObj.getString("bankBranchName");
			
			String expiredTime = resultObj.getString("expiredTime");
			
			String securityCode = resultObj.getString("securityCode");
			
			String cardType = resultObj.getString("cardType");
			
			restTemplate=new RestTemplate();
			uri = util.getServiceUrl("user", "error url request!");
			url = uri.toString() + "/v1.0/user/bank/default/cardno";
			requestEntity = new LinkedMultiValueMap<String, String>();
			requestEntity.add("cardno", bankCard);
			requestEntity.add("type", "0");
			result = restTemplate.postForObject(url, requestEntity, String.class);
			log.info("接口/v1.0/user/bank/default/cardno--RESULT================"+result);
			try {
				jsonObject =  JSONObject.fromObject(result);
				resultObj  =  jsonObject.getJSONObject("result");
			} catch (Exception e) {
				log.error("查询银行卡信息出错");
				map.put("resp_code", "failed");
				map.put("channel_type", "jfapi");
				map.put("resp_message", "查询银行卡信息有误");
				return map;
			}
			
			//充值卡持卡人姓名
			String userNames = resultObj.getString("userName");
			//充值卡手机号
			String mobile = resultObj.getString("phone");
			//充值卡身份证号
			String idCard   = resultObj.getString("idcard");
			
			
			JFApiRegister jfApiRegister = new JFApiRegister();
			try {
				jfApiRegister = topupPayChannelBusiness.getJFApiRegister(bankCard);
			} catch (Exception e) {
				log.error("根据银行卡查询商户开通信息异常"+e);
				map.put("resp_code", "failed");
				map.put("channel_type", "jfapi");
				map.put("resp_message", "查询商户开通信息异常");
				return map;
			}
			
			
			if(null != jfApiRegister){
				
				Map maps = new HashMap();
				maps.put("resp_code", "success");
				maps.put("channel_type", "jfapi");
				maps.put("redirect_url", ipAddress+"/v1.0/paymentchannel/topup/jfapipay?ordercode="+ordercode);
				return maps;
				
			}else{
				Map maps = new HashMap();
				maps.put("resp_code", "success");
				maps.put("channel_type", "jfapi");
				maps.put("redirect_url", ipAddress+"/v1.0/paymentchannel/topup/jfapiregister?userNames="+URLEncoder.encode(userNames,"UTF-8")+"&bankCard="+bankCard+
						"&mobile="+mobile+"&idCard="+idCard+"&ordercode="+ordercode);
				return maps;
			}
			
			
			
			
			
			
			
	}
	
	
	
	
	
	
	protected String execute(String key, String url, String api, String dataJson, String partnerNo, String orderId) {

		System.out.println("============ 请求报文:" + dataJson);
		String signKey = key.substring(16);
		String dataKey = key.substring(0, 16);
		String sign = DigestUtils.sha1Hex(dataJson + signKey);

		Map<String, String> params = Maps.newHashMap();
		params.put("encryptData", Base64.encode(AES.encode(dataJson, dataKey)));
		params.put("signData", sign);
		params.put("orderId", orderId);
		params.put("partnerNo", partnerNo);
		params.put("ext", "to be or not to be");

		System.out.println("encryptData : " + params.get("encryptData"));
		System.out.println("sign : " + params.get("sign"));
		System.out.println("partnerNo : " + params.get("partnerNo"));

		System.out.println("============ 请求地址:" + url + api);
		try {
			byte[] resByte = HttpClient4Util.getInstance().doPost(url + api, null, params);
			String resStr = new String(resByte, UTF_8);
			System.out.println("============ 返回报文原文:" + resStr);
			
			return resStr;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	
	public Object getHead(String ordercode, String partnerNo, String txnCode) {
		JSONObject head = new JSONObject();
		head.put("version", "1.0.0");
		head.put("charset", "UTF-8");
		head.put("partnerNo", partnerNo); // 合作方标识号
		head.put("txnCode", txnCode); // 交易代码
		head.put("orderId", ordercode); // 订单号
		head.put("reqDate", DateTime.now().toString("yyyyMMdd"));
		head.put("reqTime", DateTime.now().toString("yyyyMMddHHmmss"));
		return head;
	}
	

}
